<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="82px">
      <el-form-item label="所属学校ID" prop="schoolId">
        <el-input
            v-model="queryParams.schoolId"
            placeholder="请输入所属学校ID"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="机房名称" prop="labName">
        <el-input
            v-model="queryParams.labName"
            placeholder="请输入机房名称 (如：第一机房)"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="机房容量" prop="capacity">
        <el-input
            v-model="queryParams.capacity"
            placeholder="请输入机房容量"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="机房位置" prop="location">
        <el-input
            v-model="queryParams.location"
            placeholder="请输入机房位置"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['schoolmanage:labs:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['schoolmanage:labs:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['schoolmanage:labs:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['schoolmanage:labs:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="labsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="机房ID" align="center" prop="labId" />
      <el-table-column label="所属学校ID" align="center" prop="schoolId" />
      <el-table-column label="机房名称" align="center" prop="labName" />
      <el-table-column label="机房容量" align="center" prop="capacity" />
      <el-table-column label="机房位置" align="center" prop="location" />
      <el-table-column label="机房状态" align="center" width="120">
        <template #default="scope">
          <el-tag :type="scope.row.status === 'available' ? 'success' :
            scope.row.status === 'in_use' ? 'warning' : 'danger'">
            {{ scope.row.status === 'available' ? '可用' :
              scope.row.status === 'in_use' ? '使用中' : '维护中' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['schoolmanage:labs:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['schoolmanage:labs:remove']">删除</el-button>
          <el-button link type="primary" icon="View" @click="handleDetail(scope.row)" v-hasPermi="['schoolmanage:exams:list']">详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改机房信息对话框 -->
    <el-dialog :title="title" v-model="open" width="520px" append-to-body>
      <el-form ref="labsRef" :model="form" :rules="rules" label-width="95px">
        <el-form-item label="所属学校ID" readonly prop="schoolId">
          <el-input v-model="form.schoolId" placeholder="请输入所属学校ID" disabled/>
        </el-form-item>
        <el-form-item label="机房名称" prop="labName">
          <el-input v-model="form.labName" placeholder="请输入机房名称 (如：第一机房)" />
        </el-form-item>
        <el-form-item label="机房容量" prop="capacity">
          <el-input v-model="form.capacity" placeholder="请输入机房容量" />
        </el-form-item>
        <el-form-item label="机房位置" prop="location">
          <el-input v-model="form.location" placeholder="请输入机房位置" />
        </el-form-item>
        <el-form-item label="机房状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择机房状态">
            <el-option label="可用" value="available" />
            <el-option label="使用中" value="in_use" />
            <el-option label="维护中" value="maintenance" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Labs">
import { listLabs, getLabs, delLabs, addLabs, updateLabs,} from "@/api/schoolmanage/labs"
import { ElMessageBox, ElMessage } from 'element-plus'
import { getCurrentInstance, ref, reactive, toRefs } from 'vue'
import {useExampleStore} from "@/stores/exampleStore.js";
const { proxy } = getCurrentInstance()

const labsList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    schoolId: useExampleStore().school,
    labName: null,
    capacity: null,
    location: null,
    status: null
  },
  rules: {
    schoolId: [
      { required: true, message: "所属学校ID不能为空", trigger: "blur" }
    ],
    labName: [
      { required: true, message: "机房名称 (如：第一机房)不能为空", trigger: "blur" }
    ],
    createTime: [
      { required: true, message: "创建时间不能为空", trigger: "blur" }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询机房信息列表 */
function getList() {
  loading.value = true
  queryParams.value.schoolId = useExampleStore().school
  listLabs(queryParams.value).then(response => {
    labsList.value = response.rows
    total.value = response.total
    loading.value = false
  }).catch(error=>{
    console.error("获取列表失败：",error);
    loading.value = false;
  })
}
// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    labId: null,
    schoolId: useExampleStore().school,
    labName: null,
    capacity: null,
    location: null,
    createTime: null,
    status: "available"
  }
  proxy.resetForm("labsRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.labId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加机房信息"
}

/** 修改按钮操作 */
/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const labId = row.labId || ids.value
  getLabs(labId).then(response => {
    form.value = {
      ...response.data,
      status: response.data.status || 'available' // 确保有默认值
    }
    open.value = true
    title.value = "修改机房信息"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["labsRef"].validate(valid => {
    if (valid) {
      if (form.value.labId != null) {
        updateLabs(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addLabs(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
async function handleDelete(row) {
  const labId = row.labId;
  try {
    await ElMessageBox.confirm('确认删除该机房？', '提示', { type: 'warning' });

    // 调用删除接口
    const res = await delLabs(labId);

    if (res.success) {
      ElMessage.success("删除成功");
      getList(); // 刷新表格
    } else {
      ElMessage.error(res.errorMsg || "删除失败");
    }
  } catch (error) {
    if (error.type !== 'cancel') {
      ElMessage.error("删除失败：" + error.message);
    }
  }
}

/** 详情按钮操作 */
function handleDetail(row) {
  console.log("handleDetail - labId 原始值:", row.labId);
  console.log("handleDetail - labId 类型:", typeof row.labId);
  const labId = Number(row.labId);
  console.log("handleDetail - 转换后的 labId:", labId);
  console.log("handleDetail - 转换后的类型:", typeof labId);
  proxy.$router.push({
    name: "exams",
    query: {
      labId: row.labId
    }
  }).catch(err => {
    console.error('路由跳转失败:', err);
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('schoolmanage/labs/export', {
    ...queryParams.value
  }, `labs_${new Date().getTime()}.xlsx`)
}

getList()
</script>
